package com.liuwei.desktop.modal.repository.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.liuwei.desktop.common.DBUtils;
import com.liuwei.desktop.modal.entity.TUser;
import com.liuwei.desktop.modal.repository.UserService;

public class UserServiceImpl implements UserService{

	@Override
	public void insertUser(TUser user) throws Exception {
		String insertSql = "insert into student(name,tel) values('"+user.getName()+"','"+user.getTel()+"');";
		DBUtils.insertTable(insertSql);
	}
	
	@Override
	public void batchInsertUser(List<TUser> user) throws Exception {
		int COMMIT_SIZE = 10000;
		Connection conn = DBUtils.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement pstmt = conn.prepareStatement("insert into student(name,tel) values (?, ?)");
        for (int i = 0; i < user.size(); i++) {
            pstmt.clearParameters();
            pstmt.setString(1, user.get(i).getName());
            pstmt.setString(2, user.get(i).getTel());
            pstmt.execute();
            if ((i % COMMIT_SIZE == 0)&&(i!=0)) {
                conn.commit();
            }
        }
        conn.commit();
        conn.close();
	}

	@Override
	public List<TUser> getAllUser() throws Exception {
		List<TUser> users = new ArrayList<>();
		String insertSql = "select * from student;";
		List<HashMap<String,Object>> result = DBUtils.query(insertSql);
		if(result!=null && result.size()>0){
			for(int i=0;i<result.size();i++){
				HashMap<String,Object> row = result.get(i);
				TUser u = new TUser();
				u.setPkid((row.get("id")==null)?null:(Integer) row.get("id"));
				u.setName((row.get("name")==null)?null:(String) row.get("name"));
				u.setTel((row.get("tel")==null)?null:(String) row.get("tel"));
				users.add(u);
			}
			return users;
		}
		return null;
	}
	
	@Override
	public List<TUser> getNameLikeUser(String x) throws Exception {
		List<TUser> users = new ArrayList<>();
		String insertSql = "select * from student where name like '%"+x+"%';";
		List<HashMap<String,Object>> result = DBUtils.query(insertSql);
		if(result!=null && result.size()>0){
			for(int i=0;i<result.size();i++){
				HashMap<String,Object> row = result.get(i);
				TUser u = new TUser();
				u.setPkid((row.get("id")==null)?null:(Integer) row.get("id"));
				u.setName((row.get("name")==null)?null:(String) row.get("name"));
				u.setTel((row.get("tel")==null)?null:(String) row.get("tel"));
				users.add(u);
			}
			return users;
		}
		return null;
	}


}
